package com.yc.vote.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yc.vote.bean.Topics;
import com.yc.vote.mapper.ITopicItemMapper;
import com.yc.vote.mapper.ITopicsMapper;
import com.yc.vote.mapper.IUserInfoMapper;
import com.yc.vote.service.ITopicsService;
import com.yc.vote.util.StringUtil;

@Service
public class TopicsServiceImpl implements ITopicsService{
	@Autowired
	private ITopicsMapper topicsMapper;
	
	@Autowired
	private ITopicItemMapper topicItemMapper;
	
	@Override
	@Transactional
	public int add(Topics topics) {
		if(StringUtil.checkNull(topics.getTname(), topics.getSdate(),topics.getEdate(), topics.getUname())) {
			return -1;
		}
		
		String tid = UUID.randomUUID().toString();
		topics.setTid(tid);
		
		String[] inames = topics.getUname().split("\\$");
		topics.setUname("");
		
		List<String> sqlIds = Arrays.asList("TopicsMapper.add", "TopicItemMapper.add");
		List<Object> params = new ArrayList<Object>();
		params.add(topics);
		
		List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		for(String iname : inames) {
			map = new HashMap<String, Object>();
			map.put("tid", tid);
			map.put("iname", iname);
			items.add(map);
		}
		
		//添加投票主体
		int result = topicsMapper.add(topics);
		
		//添加投票选项
		result = topicItemMapper.add(items);
		
		return result;
	}

	@Override
	public List<Topics> findAll() {
		return topicsMapper.findAll();
	}

	@Override
	public Topics findByTid(String tid) {
		if(StringUtil.checkNull(tid)) {
			return null;
		}
		return topicsMapper.findByTid(tid);
	}

	@Override
	@Transactional
	public int update(String tid, int usid, String inos) {
		if(StringUtil.checkNull(tid, inos)) {
			return -1;
		}
		
		List<String> sqlIds = Arrays.asList("TopicsMapper.update", "TopicItemMapper.update");
		List<Object> params = new ArrayList<Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tid", tid);
		map.put("usid", usid);

		int result = topicsMapper.update(map);
		result = topicItemMapper.update(inos.split(","));
		
		return result;
	}
	
}
